<template>
  <div class="api-docs">
    <div class="page-header">
      <h2>API接口文档</h2>
    </div>
    
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    />
    
    <el-card class="filter-card">
      <div class="filter-container">
        <el-select
          v-model="selectedModel"
          placeholder="选择模型"
          clearable
          @change="generateApiDocs"
          style="width: 250px;"
        >
          <el-option
            v-for="model in models"
            :key="model.id"
            :label="model.displayName || model.name"
            :value="model.name"
          />
        </el-select>
        
        <el-button
          type="primary"
          @click="generateApiDocs"
          :disabled="!selectedModel"
        >
          生成接口文档
        </el-button>
      </div>
    </el-card>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <template v-else-if="selectedModel && apiDocs.length > 0">
      <el-card v-for="(doc, index) in apiDocs" :key="index" class="api-card">
        <template #header>
          <div class="api-header">
            <div class="method-badge" :class="getMethodClass(doc.method)">
              {{ doc.method }}
            </div>
            <div class="api-title">{{ doc.title }}</div>
          </div>
        </template>
        
        <div class="api-content">
          <div class="api-section">
            <h4>请求URL</h4>
            <el-input
              :value="doc.url"
              readonly
              class="code-input"
            >
              <template #append>
                <el-button @click="copyToClipboard(doc.url)">
                    <el-icon><CopyDocument /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
          
          <div class="api-section">
            <h4>请求方法</h4>
            <p>{{ doc.method }}</p>
          </div>
          
          <div v-if="doc.params && doc.params.length > 0" class="api-section">
            <h4>URL参数</h4>
            <el-table :data="doc.params" border style="width: 100%">
              <el-table-column prop="name" label="参数名" width="180" />
              <el-table-column prop="type" label="类型" width="120" />
              <el-table-column prop="required" label="必填" width="80">
                <template #default="scope">
                  {{ scope.row.required ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" />
            </el-table>
          </div>
          
          <div v-if="doc.body && doc.body.length > 0" class="api-section">
            <h4>请求体</h4>
            <el-table :data="doc.body" border style="width: 100%">
              <el-table-column prop="name" label="字段名" width="180" />
              <el-table-column prop="type" label="类型" width="120" />
              <el-table-column prop="required" label="必填" width="80">
                <template #default="scope">
                  {{ scope.row.required ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" />
            </el-table>
          </div>
          
          <div class="api-section">
            <h4>响应示例</h4>
            <div class="code-block">
              <pre>{{ doc.response }}</pre>
              <el-button 
                class="copy-button" 
                size="small" 
                @click="copyToClipboard(doc.response)"
              >
               <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
          </div>
          
          <div class="api-section">
            <h4>JavaScript调用示例</h4>
            <div class="code-block">
              <pre>{{ doc.jsExample }}</pre>
              <el-button 
                class="copy-button" 
                size="small" 
                @click="copyToClipboard(doc.jsExample)"
              >
               <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
          </div>
          
          <div v-if="doc.notes" class="api-section">
            <h4>备注</h4>
            <p>{{ doc.notes }}</p>
          </div>
        </div>
      </el-card>
    </template>
    
    <el-empty 
      v-else-if="!loading && selectedModel" 
      description="暂无接口文档，请选择模型并生成文档"
    />
    
    <el-empty 
      v-else-if="!loading" 
      description="请选择一个模型来查看接口文档"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useModelStore } from '../stores/model'
import { ElMessage } from 'element-plus'

const modelStore = useModelStore()
const models = computed(() => modelStore.models)
const loading = ref(false)
const error = ref(null)
const selectedModel = ref('')
const apiDocs = ref([])

// 获取模型列表
onMounted(async () => {
  try {
    loading.value = true
    error.value = null
    await modelStore.fetchModels()
  } catch (err) {
    console.error('获取模型列表失败:', err)
    error.value = `获取模型列表失败: ${err.message}`
  } finally {
    loading.value = false
  }
})

// 根据HTTP方法获取样式类
function getMethodClass(method) {
  switch (method.toUpperCase()) {
    case 'GET': return 'method-get'
    case 'POST': return 'method-post'
    case 'PUT': return 'method-put'
    case 'DELETE': return 'method-delete'
    default: return ''
  }
}

// 复制内容到剪贴板
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败')
  }
}

// 生成API文档
async function generateApiDocs() {
  if (!selectedModel.value) {
    apiDocs.value = []
    return
  }
  
  try {
    loading.value = true
    error.value = null
    
    const model = modelStore.getModelByName(selectedModel.value)
    if (!model) {
      throw new Error(`找不到模型: ${selectedModel.value}`)
    }
    
    const baseUrl = window.location.origin + '/api'
    const docs = []
    
    // 获取列表接口
    docs.push({
      title: `获取${model.displayName || model.name}列表`,
      method: 'GET',
      url: `${baseUrl}/data/${model.name}`,
      params: [
        { name: 'page', type: '数字', required: false, description: '页码，默认为1' },
        { name: 'pageSize', type: '数字', required: false, description: '每页记录数，默认为10' },
        { name: 'sort', type: '字符串', required: false, description: '排序字段，例如: "id:desc"' },
        { name: 'filter', type: '字符串', required: false, description: '过滤条件，例如: "name:like:测试"' }
      ],
      response: JSON.stringify({
        data: generateSampleData(model, 2),
        total: 100,
        page: 1,
        pageSize: 10,
        totalPages: 10
      }, null, 2),
      jsExample: `// 使用axios
axios.get('${baseUrl}/data/${model.name}', {
  params: {
    page: 1,
    pageSize: 10,
    sort: 'id:desc',
    filter: 'name:like:测试'
  }
})
.then(response => console.log(response.data))
.catch(error => console.error(error))

// 使用fetch
fetch('${baseUrl}/data/${model.name}?page=1&pageSize=10&sort=id:desc&filter=name:like:测试')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))`
    })
    
    // 获取单条记录接口
    docs.push({
      title: `获取单个${model.displayName || model.name}`,
      method: 'GET',
      url: `${baseUrl}/data/${model.name}/1`,
      params: [
        { name: 'id', type: '数字/字符串', required: true, description: '记录ID' }
      ],
      response: JSON.stringify(generateSampleData(model, 1)[0], null, 2),
      jsExample: `// 使用axios
axios.get('${baseUrl}/data/${model.name}/1')
  .then(response => console.log(response.data))
  .catch(error => console.error(error))

// 使用fetch
fetch('${baseUrl}/data/${model.name}/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))`
    })
    
    // 创建记录接口
    docs.push({
      title: `创建${model.displayName || model.name}`,
      method: 'POST',
      url: `${baseUrl}/data/${model.name}`,
      body: Array.isArray(model.fields) ? model.fields.map(field => ({
        name: field.name,
        type: field.type,
        required: field.required,
        description: field.description || `${field.displayName || field.name}字段`
      })) : [],
      response: JSON.stringify(generateSampleData(model, 1)[0], null, 2),
      jsExample: `// 使用axios
const data = ${JSON.stringify(generateSampleRequestBody(model), null, 2)}

axios.post('${baseUrl}/data/${model.name}', data)
  .then(response => console.log(response.data))
  .catch(error => console.error(error))

// 使用fetch
fetch('${baseUrl}/data/${model.name}', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))`
    })
    
    // 更新记录接口
    docs.push({
      title: `更新${model.displayName || model.name}`,
      method: 'PUT',
      url: `${baseUrl}/data/${model.name}/1`,
      params: [
        { name: 'id', type: '数字/字符串', required: true, description: '记录ID' }
      ],
      body: Array.isArray(model.fields) ? model.fields.map(field => ({
        name: field.name,
        type: field.type,
        required: field.required,
        description: field.description || `${field.displayName || field.name}字段`
      })) : [],
      response: JSON.stringify(generateSampleData(model, 1)[0], null, 2),
      jsExample: `// 使用axios
const data = ${JSON.stringify(generateSampleRequestBody(model), null, 2)}

axios.put('${baseUrl}/data/${model.name}/1', data)
  .then(response => console.log(response.data))
  .catch(error => console.error(error))

// 使用fetch
fetch('${baseUrl}/data/${model.name}/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))`
    })
    
    // 删除记录接口
    docs.push({
      title: `删除${model.displayName || model.name}`,
      method: 'DELETE',
      url: `${baseUrl}/data/${model.name}/1`,
      params: [
        { name: 'id', type: '数字/字符串', required: true, description: '记录ID' }
      ],
      response: JSON.stringify({ success: true }, null, 2),
      jsExample: `// 使用axios
axios.delete('${baseUrl}/data/${model.name}/1')
  .then(response => console.log(response.data))
  .catch(error => console.error(error))

// 使用fetch
fetch('${baseUrl}/data/${model.name}/1', {
  method: 'DELETE'
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))`,
      notes: '删除操作不可恢复，请谨慎操作。'
    })
    
    apiDocs.value = docs
  } catch (err) {
    console.error('生成API文档失败:', err)
    error.value = `生成API文档失败: ${err.message}`
  } finally {
    loading.value = false
  }
}

// 生成示例数据
function generateSampleData(model, count) {
  const result = []
  
  for (let i = 0; i < count; i++) {
    const item = {
      id: i + 1
    }
    
    // 确保 model.fields 是数组
    const fields = Array.isArray(model.fields) ? model.fields : []
    
    for (const field of fields) {
      switch (field.type) {
        case 'string':
          item[field.name] = `示例${field.displayName || field.name} ${i + 1}`
          break
        case 'text':
          item[field.name] = `这是一段${field.displayName || field.name}示例文本内容 ${i + 1}`
          break
        case 'integer':
          item[field.name] = (i + 1) * 100
          break
        case 'float':
          item[field.name] = (i + 1) * 10.5
          break
        case 'boolean':
          item[field.name] = i % 2 === 0
          break
        case 'date':
          item[field.name] = new Date().toISOString().split('T')[0]
          break
        case 'datetime':
          item[field.name] = new Date().toISOString()
          break
        default:
          item[field.name] = `示例值 ${i + 1}`
      }
    }
    
    result.push(item)
  }
  
  return result
}

// 生成示例请求体
function generateSampleRequestBody(model) {
  const body = {}
  
  // 确保 model.fields 是数组
  const fields = Array.isArray(model.fields) ? model.fields : []
  
  for (const field of fields) {
    // 跳过id字段，通常由服务器生成
    if (field.name === 'id') continue
    
    switch (field.type) {
      case 'string':
        body[field.name] = `示例${field.displayName || field.name}`
        break
      case 'text':
        body[field.name] = `这是一段${field.displayName || field.name}示例文本内容`
        break
      case 'integer':
        body[field.name] = 100
        break
      case 'float':
        body[field.name] = 10.5
        break
      case 'boolean':
        body[field.name] = true
        break
      case 'date':
        body[field.name] = new Date().toISOString().split('T')[0]
        break
      case 'datetime':
        body[field.name] = new Date().toISOString()
        break
      default:
        body[field.name] = '示例值'
    }
  }
  
  return body
}
</script>

<style scoped>
.api-docs {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  gap: 16px;
  align-items: center;
}

.loading-container {
  margin-top: 20px;
}

.api-card {
  margin-bottom: 20px;
}

.api-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.method-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 14px;
  min-width: 60px;
  text-align: center;
}

.method-get {
  background-color: #61affe;
  color: white;
}

.method-post {
  background-color: #49cc90;
  color: white;
}

.method-put {
  background-color: #fca130;
  color: white;
}

.method-delete {
  background-color: #f93e3e;
  color: white;
}

.api-title {
  font-size: 16px;
  font-weight: bold;
}

.api-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.api-section h4 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #606266;
}

.code-input {
  font-family: monospace;
}

.code-block {
  position: relative;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 16px;
  overflow: auto;
}

.code-block pre {
  margin: 0;
  font-family: monospace;
  white-space: pre-wrap;
}

.copy-button {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0.7;
}

.copy-button:hover {
  opacity: 1;
}
</style> 